import { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import MenuContext from '@/context/MenuContext';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, message, Form, Input } from 'antd';
import { authCodeAPI, loginByCodeAPI } from '../../utils/api'
import './login.sass'
type FieldType = {
  username?: string;
  pass?: string;
  verifyCode?: string;
  token?: string;
};

const Login = () => {

  const navigate = useNavigate();
  const { setMenu } = useContext(MenuContext);
  // const [messageApi] = message.useMessage();
  const [authImgCode, setAuthImgCode] = useState({
    imageCode: "",
    token: ""
  })

  const getImgCode = async () => {
    const res = await authCodeAPI();
    if (res.errCode == 10000) {
      setAuthImgCode({ imageCode: res.imageCode, token: res.token });
    }
  }
  useEffect(() => {

    getImgCode();
  }, [])

  const onFinish = async (values: any) => {

    let data = { ...values, token: authImgCode.token }
    const res = await loginByCodeAPI(data);
    if (res.errCode == 10000) {
      sessionStorage.setItem('token', res.data.token);
      setMenu(res.data.menu)
      navigate('/main/home');
    }
    else {
      message.error(res.errMsg ?? "请求失败");
      getImgCode();
    }

  }


  return (
    <div  className='loginbody'>

      <Form
       
        name="basic"
        labelCol={{ span: 10 }}
        // wrapperCol={{ span: 18 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        // onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label=""
          name="username"
          rules={[{ required: true, message: '请输入账号!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} />
        </Form.Item>

        <Form.Item<FieldType>
          label=""
          name="pass"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} />
        </Form.Item>


        <Form.Item>
          <div style={{ display: "flex" }}>
            <Form.Item<FieldType>
              label=""
              name="verifyCode"
              rules={[{ required: true, message: '请输入图形验证码!' }]}
            >
              <Input style={{ width: "200px" }} prefix={<LockOutlined className="site-form-item-icon" />} />

            </Form.Item>
            <img onClick={getImgCode} style={{ height: "50px" }} src={authImgCode.imageCode} />
          </div>

        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
 
    </div>
  );
}
export default Login;
